<?php

	namespace Home\Controller;
	use THink\Controller;

	class UploadController extends Controller {

		// public function uploadPage() {
		// 	if (isset($_SESSION['uid'])) {
		// 		$condition = 1;
		// 		$whichTag = 4;
		// 		$this->assign('whichTag', $whichTag);
		// 		$this->assign('username', $_SESSION['username']);
		// 		$this->assign('condition', $condition);
		// 		$this->display();
		// 	}
		// 	else {
		// 		$condition = 0;
		// 		$this->error('您还未登录，正在跳转至系统首页...', U('Blast/blast'), 1);
		// 	}
		// }

		public function upload() {
			if (isset($_SESSION['uid'])) {
				$data = array();

				$data['species']  = I('post.species');
				$data['primerid'] = $data['species'] .'_' . mt_rand();
				$data['user'] = $_SESSION['username'];
				$data['gene']  = trim(I('post.gene'));
				$data['forwardprimer']  = strtoupper(trim(I('post.forwardprimer')));
				$data['reverseprimer']  = strtoupper(trim(I('post.reverseprimer')));
				$data['tm']  = trim(I('post.tm'));
				$data['productgc']  = trim(I('post.productgc'));
				$data['productlength']  = trim(I('post.productlength'));
				$data['uploaddate']  =  date('Y-m-d H:i:s', time());
				$data['location']  = trim(I('post.location'));
				$data['identifier']  = trim(I('post.identifier'));
				$data['describe']  = trim(I('post.describe'));

				// var_dump($data);
				$addResult = M('search')->data($data)->add();
				if ($addResult) {
					// var_dump($data);
					$result[0] = $data;
					$result = base64_encode(serialize($result));
					// var_dump($result);

					if (!($data['forwardprimer'] == '-')) {
						$pidForward = $data['primerid'] . '_forward';
						shell_exec("python D:/wamp64/www/" . __ROOT__ . "/public/python/upload_fasta.py -id " . $pidForward . " -gene " . $data['gene'] . " -fprimer " . $data['forwardprimer']);
					}

					if (!($data['reverseprimer'] == '-')) {
						$pidReverse = $data['primerid'] . '_reverse';
						shell_exec("python D:/wamp64/www/" . __ROOT__ . "/public/python/upload_fasta.py -id " . $pidReverse . " -gene " . $data['gene'] . " -fprimer " . $data['reverseprimer']);
					}

					// $this->success('上传成功，正跳转至上传首页...', U('upload/uploadPage'), 1);
					$this->redirect('search/uploadResult', "species=" . $data['species'] . "&gene=" .$data['gene'] ."&forwardprimer=" . $data['forwardprimer'] . "&reverseprimer=" . $data['reverseprimer'] . "&result=$result", 3, '<br /><h1>处理成功，3秒后跳转至上传结果页面...</h1>');
				}
				else {
					$this->error('上传失败');
				}
			}
			else {
				$condition = 0;
				$this->error('您还未登录，正在跳转至系统首页...', U('Blast/blast'), 1);
			}
		}

		public function uploadFile() {
			if (isset($_SESSION['uid'])) {

				if(!empty($_FILES)) {
					// var_dump($_FILES);
					$upload = new \Think\Upload();// 实例化上传类
					$upload->maxSize = 3 * 1024 * 1024 ;// 设置附件上传大小
					$upload->exts = array('csv');// 设置附件上传类型
					$upload->rootPath = 'D:/wamp64/www' . __ROOT__; // 设置附件上传根目录
					$upload->savePath = '/Public/uploads/'; // 设置附件上传（子）目录 // 上传文件
					$fileName = $_FILES["file"]["name"];//这样就能够取得上传的文件名
			        $fileExtensions = '.csv';
			        $serverFileName = basename($fileName, $fileExtensions)."_".date("Ymd")."_".mt_rand();
			        $upload->saveName = $serverFileName;//设置在服务器保存的文件名

					$info = $upload->upload();
					if(!$info) {// 上传错误提示错误信息
						$this->error($upload->getError());
					}
					else {// 上传成功
						echo ('<div id="upload-result"><p><h1>上传成功，正在处理中...</h1></p>');
						// var_dump($info);

						$filepath = 'D:/wamp64/www' .__ROOT__ . $info['file']['savepath'] . $info['file']['savename'];
						$count = 0;

						$_SESSION['fileName'] = $fileName;

						if (($handle = fopen($filepath, "r")) !== FALSE) {
							$_SESSION['successCount'] = 0;
							$_SESSION['successData'] = array();
							$_SESSION['failCount'] = 0;
							$_SESSION['failData'] = array();
						    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
						        // var_dump((int)$data[0]);
						        // 过滤第一行字段
						        if ((int)$data[0] == 0) {
						        	continue;
						        }
						        else {
						        	// 过滤基因序列格式不对的
						        	// var_dump($data);
						        	$pregErr = array();
					        		$pregErr['primerid'] = trim($data[1]);
					        		$pregErr['gene'] = trim($data[2]);
						        	$pregErr['species'] = trim($data[3]);
						        	$pregErr['forwardprimer'] = $data[4]? strtoupper(trim($data[4])) : '-';
						        	$pregErr['reverseprimer'] = $data[5]? strtoupper(trim($data[5])) : '-';
						        	$pregErr['tm'] = $data[6]? trim($data[6]) : '-';
						        	$pregErr['productgc'] = $data[7]? trim($data[7]) : '-';
						        	$pregErr['productlength'] = $data[8]? trim($data[8]) : '-';
						        	$pregErr['describe'] = $data[9]? trim($data[9]) : '-';
						        	$pregErr['location'] = $data[10]? trim($data[10]) : '-';
						        	$pregErr['identifier'] = $data[11]? trim($data[11]) : '-';
						        	$pregErr['user'] = $data[12]? trim($data[12]) : '-';
						        	$pregErr['uploaddate'] = $data[13]? trim($data[13]) : '-';

						        	$pattern = '/^[AaCcTtGg-]+$/i';
						        	if (empty(preg_match($pattern, $pregErr['forwardprimer'], $matches4)) || empty(preg_match($pattern, $pregErr['reverseprimer'], $matches5))) {

							        	$pregErr['errorMsg'] = "引物格式有误！";
						        		$_SESSION['failCount'] ++;
						        		$_SESSION['failData'][$count] = $pregErr;

						    			$count ++;
						        		continue;
						        	}
						        	// var_dump($matches4);
						        	// var_dump($matches5);

						        	$pattern = '/^[-]+$/i';
						        	if (!(empty(preg_match($pattern, $pregErr['forwardprimer'], $matches4))) && !(empty(preg_match($pattern, $pregErr['reverseprimer'], $matches5)))) {

							        	$pregErr['errorMsg'] = "引物不可同时为空！";
						        		$_SESSION['failCount'] ++;
						        		$_SESSION['failData'][$count] = $pregErr;

						    			$count ++;
						        		continue;
						        	}

						        	// 过滤loc不正确的
						        	$pattern = '/^(loc)|(\-)$/';
						        	$prefix = explode('_', $pregErr['location'])[0];
						        	if (empty(preg_match($pattern, $prefix, $matches4))) {
							        	$pregErr['errorMsg'] = "location/identifier格式有误！";
						        		$_SESSION['failCount'] ++;
						        		$_SESSION['failData'][$count] = $pregErr;

						    			$count ++;
						        		continue;
						        	}
						        	// 过滤id不正确的
						        	$pattern = '/^(id)|(-)$/';
						        	$prefix = explode('_', $pregErr['identifier'])[0];
						        	if (empty(preg_match($pattern, $prefix, $matches4))) {
							        	$pregErr['errorMsg'] = "identifier格式有误！";
						        		$_SESSION['failCount'] ++;
						        		$_SESSION['failData'][$count] = $pregErr;

						    			$count ++;
						        		continue;
						        	}

							    	$where = array();
							    	$where['primerid'] = trim($data[1]);
							    	if (M('search')->where($where)->select()) {
							    		$where['gene'] = $data[2];
							        	$where['species'] = $data[3];
							        	$where['forwardprimer'] = $data[4]? strtoupper(trim($data[4])) : '-';
							        	$where['reverseprimer'] = $data[5]? strtoupper(trim($data[5])) : '-';
						    			$where['tm'] = $data[6]? trim($data[6]) : '-';
							        	$where['productgc'] = $data[7]? trim($data[7]) : '-';
							        	$where['productlength'] = $data[8]? trim($data[8]) : '-';
							        	$where['describe'] = $data[9]? trim($data[9]) : '-';
							        	$where['location'] = $data[10]? trim($data[10]) : '-';
							        	$where['identifier'] = $data[11]? trim($data[11]) : '-';
							        	$where['user'] = $data[12]? trim($data[12]) : '-';
							        	$where['uploaddate'] = $data[13]? trim($data[13]) : '-';
							        	$where['errorMsg'] = "Primer ID 已存在！";
							        	$_SESSION['failCount'] ++;
						        		$_SESSION['failData'][$count] = $where;
							    	}
							    	else {
							    		$where['gene'] = $data[2];
							        	$where['species'] = $data[3];
							        	$where['forwardprimer'] = $data[4]? strtoupper(trim($data[4])) : '-';
							        	$where['reverseprimer'] = $data[5]? strtoupper(trim($data[5])) : '-';

							        	$searchResult = M('search')->where($where)->select();
							        	// $searchResult = false;
							        	// 过滤已有的
							        	if ($searchResult) {
							        		$where['tm'] = $data[6]? trim($data[6]) : '-';
								        	$where['productgc'] = $data[7]? trim($data[7]) : '-';
								        	$where['productlength'] = $data[8]? trim($data[8]) : '-';
								        	$where['describe'] = $data[9]? trim($data[9]) : '-';
								        	$where['location'] = $data[10]? trim($data[10]) : '-';
								        	$where['identifier'] = $data[11]? trim($data[11]) : '-';
								        	$where['user'] = $data[12]? trim($data[12]) : '-';
								        	$where['uploaddate'] = $data[13]? trim($data[13]) : '-';
								        	$where['errorMsg'] = "该引物已存在！";
								        	$_SESSION['failCount'] ++;
							        		$_SESSION['failData'][$count] = $where;
							        		// $failCount ++;
							        		// $failData[$count] = $where;
							        		// echo "<h2>existed</h2>";
							        	}
							        	else {
						        			$condition = array();
											$condition['id'] = 0;
											$condition['primerid'] = trim($data[1]);
								        	$condition['gene'] = trim($data[2]);
								        	$condition['species'] = trim($data[3]);
								        	$condition['forwardprimer'] = $data[4]? strtoupper(trim($data[4])) : '-';
							        		$condition['reverseprimer'] = $data[5]? strtoupper(trim($data[5])) : '-';
								        	$condition['tm'] = $data[6]? trim($data[6]) : '-';
								        	$condition['productgc'] = $data[7]? trim($data[7]) : '-';
								        	$condition['productlength'] = $data[8]? trim($data[8]) : '-';
								        	$condition['describe'] = $data[9]? trim($data[9]) : '-';
								        	$condition['location'] = $data[10]? trim($data[10]) : '-';
								        	$condition['identifier'] = $data[11]? trim($data[11]) : '-';
								        	$condition['user'] = $data[12]? trim($data[12]) : '-';
								        	$condition['uploaddate'] = $data[13]? trim($data[13]) : date('Y-m-d H:i:s', time());

								        	// var_dump($condition);
								        	$addResult = M('search')->data($condition)->add();
								        	// $addResult = false;
								        	if ($addResult) {
								        		if (!($condition['forwardprimer'] == '-')) {
													$pidForward = $condition['primerid'] . '_forward';
													shell_exec("python D:/wamp64/www/" . __ROOT__ . "/public/python/upload_fasta.py -id " . $pidForward . " -gene " . $condition['gene'] . " -fprimer " . $condition['forwardprimer']);
												}

												if (!($condition['reverseprimer'] == '-')) {
													$pidReverse = $condition['primerid'] . '_reverse';
													shell_exec("python D:/wamp64/www/" . __ROOT__ . "/public/python/upload_fasta.py -id " . $pidReverse . " -gene " . $condition['gene'] . " -fprimer " . $condition['reverseprimer']);
												}
								        		// shell_exec("python D:/wamp64/www/" . __ROOT__ . "/public/python/upload_fasta.py -id " . $condition['primerid'] . " -gene " . $condition['gene'] . " -fprimer " . $condition['forwardprimer']);
								        		// var_dump("python " . __ROOT__ . "/public/python/upload_fasta.py -id " . $condition['identifier'] . " -gene " . $condition['gene'] . " -fprimer " . $condition['forwardprimer']);

								        		$_SESSION['successCount'] ++;
							        			$_SESSION['successData'][$count] = $condition;
								        	}
								        	else {
								        		$condition['errorMsg'] = '上传失败';
								        		$_SESSION['failCount'] ++;
							        			$_SESSION['failData'][$count] = $condition;
								        	}
							        	}
							    	}
						        }
						        $count ++;
						    }
						    fclose($handle);
						 	$this->redirect('upload/uploadFileResult', "", 3 , '<br /><h1>处理成功，3秒后跳转至上传结果页面...</h1>');
						}
						else {
							echo "error";
						}
					}
				}
			}
			else {
				$condition = 0;
				$this->error('您还未登录，正在跳转至系统首页...', U('Blast/blast'), 1);
			}
		}

		public function uploadFileResult() {
			if (isset($_SESSION['uid'])) {
				// var_dump($_SESSION);

				$failCount = $_SESSION['failCount'];
				$successCount = $_SESSION['successCount'];
				$failData = $_SESSION['failData'];
				$successData = $_SESSION['successData'];

				$fileName = $_SESSION['fileName'];
				$condition = 1;
				$whichTag = 3;

				$this->assign('fileName', $fileName);
				$this->assign('successCount', $successCount);
				$this->assign('failCount', $failCount);
				$this->assign('failData', $failData);
				$this->assign('successData', $successData);
				$this->assign('condition', $condition);
				$this->assign('whichTag', $whichTag);
				$this->assign('uploadcondition', 1);
				$this->display();
			}
			else {
				$condition = 0;
				$this->error('您还未登录，正在跳转至系统首页...', U('Blast/blast'), 1);
			}
		}

		// public function primerCheck() {
		// 	// 保留用于判断引物是否存在
		// 	$search = D('search');
		// 	$species = I('get.species');
		// 	$name = I('get.name');
		// 	$primer = I('get.primer');
		// 	$url = __ROOT__;

		// 	$condition[$name] = $primer;
		// 	$condition['species'] = $species;
		// 	$result = $search->where($condition)->select();
		// 	// var_dump($condition);
		// 	if ($result){
		// 		$data['hasprimer'] = true;
		// 		$url .= "/home/Search/uploadResult?name=$name&primer=$primer&result=" . base64_encode(serialize($result));
		// 		$data['url'] = $url;
		// 	}
		// 	else {
		// 		$data['hasprimer'] = false;
		// 	}
		// 	$this->ajaxReturn($data);
		// }

		public function uploadCheck() {
			if (I('get.species')) {
				$search = D('search');
				$species = I('get.species');
				$gene = trim(I('get.gene'));
				$forwardprimer = trim(I('get.forwardprimer'));
				$reverseprimer = trim(I('get.reverseprimer'));

				$condition['species'] = $species;
				$condition['gene'] = $gene;
				// $where['forwardprimer'] = I('get.forwardprimer');
				// $where['reverseprimer'] = I('get.reverseprimer');
				// $where['_logic'] = 'or';
				$condition['forwardprimer'] = $forwardprimer;
				$condition['reverseprimer'] = $reverseprimer;
				// $condition['_complex'] = $where;

				$result = $search->where($condition)->select();
				// var_dump($result);

				$url = __ROOT__;
				if ($result){
					$data['hasprimer'] = true;
					$url .= "/home/Search/uploadResult?species=$species&gene=$gene&forwardprimer=$forwardprimer&reverseprimer=$reverseprimer&result=" . base64_encode(serialize($result));
					$data['url'] = $url;
				}
				else {
					$data['hasprimer'] = false;
				}
				$this->ajaxReturn($data);
			}
		}
	}
?>
